//
//  UIView+LayerEffects.m
//
//  Created by Water Lou on 15/09/2010.
//  Copyright 2010 First Water Tech Ltd. All rights reserved.
//

#import <QuartzCore/QuartzCore.h>
#import "UIView+HG.h"
#import "MBProgressHUD.h"
#import <objc/runtime.h>

static char sUIViewTapBlockStorageKey ;

@implementation UIView(HG)

/* simple setting using the layer */
- (void) setCornerRadius : (CGFloat) radius {
    self.layer.masksToBounds = YES;
	self.layer.cornerRadius = radius;
}

- (void) setBorder : (UIColor *) color width : (CGFloat) width  {
	self.layer.borderColor = [color CGColor];
	self.layer.borderWidth = width;
}


- (void)addBorderWithColor:(UIColor *)color size:(CGFloat)size borderTypes:(NSArray *)types{
    for (int i = 0 ; i < types.count; i ++) {
        [self addBorderLayerWithColor:color size:size borderType:[types[i] integerValue]];
    }
}

- (void)addBorderLayerWithColor:(UIColor *)color size:(CGFloat)size borderType:(BorderType)boderType{
    CALayer * layer = [CALayer layer];
    layer.backgroundColor = color.CGColor;
    [self.layer addSublayer:layer];
    
    switch (boderType) {
        case BorderTypeTop:
            layer.frame = CGRectMake(0, 0, self.frame.size.width, size);
            break;
        case BorderTypeLeft:
            layer.frame = CGRectMake(0, 0, size, self.frame.size.height);
            break;
        case BorderTypeBottom:
            layer.frame = CGRectMake(0, self.frame.size.height - size, self.frame.size.width, size);
            break;
        case BorderTypeRight:
            layer.frame = CGRectMake(self.frame.size.width - size, 0, size, self.frame.size.height);
            break;
        default:
            break;
    }
    
}

- (void) setShadow : (UIColor *)color opacity:(CGFloat)opacity offset:(CGSize)offset blurRadius:(CGFloat)blurRadius {
	CALayer *l = self.layer;
	l.shadowColor = [color CGColor];
	l.shadowOpacity = opacity;
	l.shadowOffset = offset;
	l.shadowRadius = blurRadius;
}


+ (id)inflate:(NSString *)xib owner:(id)owner
{
    return [[[NSBundle mainBundle] loadNibNamed:xib owner:owner options:nil] objectAtIndex:0];
}


- (id)findFirstResponderView
{
    if ([self isFirstResponder])
    {
        return self;
    }
    for (UIView *subview in self.subviews)
    {
        UIView *firstResponderView = [subview findFirstResponderView];
        if (firstResponderView)
            return firstResponderView;
    }
    return nil;
}

- (BOOL)containsView:(UIView *)view
{
    while (view)
    {
        if (view == self)
            return YES;
        view = view.superview;
    }
    return NO;
}

- (id)superViewOf:(Class)viewClass {
    id view = self;
    while (view)
    {
        if ([view isKindOfClass:viewClass])
            return view;
        view = [view superview];
    }
    return nil;
}

- (void)addVerticalItemViews:(NSArray<UIView*>*)itemViews
                withSepColor:(UIColor*)sepColor
                      topSep:(BOOL)top//是否在最上方添加sep
                   bottomSep:(BOOL)bottom //是否在最下方添加sep
                    hPadding:(CGFloat)hPadding//水平方向的间隔
               minItemHeight:(CGFloat)minItemHeight//item的最小高度
{
    if (itemViews.count == 0) {
        return;
    }
    
    UIView *contentView = self;
    if (sepColor == nil) {
        sepColor = [UIColor clearColor];
    }
    CGFloat sepHeight = 1.0 / [UIScreen mainScreen].scale;
    NSMutableString *v_vfl = [NSMutableString string];
    NSMutableDictionary *v_views = [NSMutableDictionary dictionary];
    [v_vfl appendFormat:@"V:|-0-"];
    
    void(^sepBlock)(NSInteger) = ^(NSInteger index){
        NSString *sepName = [NSString stringWithFormat:@"sep%ld",index];
        UIView *sep = [[UIView alloc] init];
        sep.backgroundColor = sepColor;
        sep.translatesAutoresizingMaskIntoConstraints=NO;
        [contentView addSubview:sep];
        NSString *hFmt = [NSString stringWithFormat:@"H:|-%.2f-[sep]-%.2f-|", hPadding, hPadding];
        [contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:hFmt options:0 metrics:nil views:@{@"sep":sep}]];
        [v_vfl appendFormat:@"[%@(==%.2f)]-0-",sepName, sepHeight];
        [v_views setObject:sep forKey:sepName];
    };
    
    if (top) {
        sepBlock(0);
    }
    
    for (int i = 0; i < itemViews.count ; i++) {
        UIView *v = itemViews[i];
        v.translatesAutoresizingMaskIntoConstraints=NO;
        NSString *vName = [NSString stringWithFormat:@"v%d",i];
        if (minItemHeight > 0) {
            [v_vfl appendFormat:@"[%@(>=%.2f@1000)]-0-",vName, minItemHeight];
        } else {
            [v_vfl appendFormat:@"[%@]-0-",vName];
        }
        [v_views setObject:v forKey:vName];
        
        if (i < itemViews.count - 1) {
            sepBlock(i+1);
        }
        
        [contentView addSubview:v];
        [contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[v]-0-|" options:0 metrics:nil views:@{@"v":v}]];
    }
    
    if (bottom) {
        sepBlock(itemViews.count);
    }
    
    [v_vfl appendFormat:@"|"];
    [contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:v_vfl options:0 metrics:nil views:v_views]];
}

- (void)addVerticalItemViews:(NSArray<UIView *> *)itemViews withSepColor:(UIColor *)sepColor topSep:(BOOL)top bottomSep:(BOOL)bottom hPadding:(CGFloat)hPadding {
    [self addVerticalItemViews:itemViews withSepColor:sepColor topSep:top bottomSep:bottom hPadding:hPadding minItemHeight:-1];
}


- (void)setTapBlock:(dispatch_block_t)block {    
    objc_setAssociatedObject(self, &sUIViewTapBlockStorageKey, block, OBJC_ASSOCIATION_COPY_NONATOMIC);
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:[UIView class] action:@selector(_private_static_on_tap:)];
    [self addGestureRecognizer:tap];
}

+ (void)_private_static_on_tap:(UITapGestureRecognizer*)tap {
    dispatch_block_t block = objc_getAssociatedObject(tap.view, &sUIViewTapBlockStorageKey);
    if (block) {
        block();
    }
}


- (CGFloat)left {
    return self.frame.origin.x;
}



- (void)setLeft:(CGFloat)x {
    CGRect frame = self.frame;
    frame.origin.x = x;
    self.frame = frame;
}



- (CGFloat)top {
    return self.frame.origin.y;
}



- (void)setTop:(CGFloat)y {
    CGRect frame = self.frame;
    frame.origin.y = y;
    self.frame = frame;
}



- (CGFloat)right {
    return self.frame.origin.x + self.frame.size.width;
}



- (void)setRight:(CGFloat)right {
    CGRect frame = self.frame;
    frame.origin.x = right - frame.size.width;
    self.frame = frame;
}



- (CGFloat)bottom {
    return self.frame.origin.y + self.frame.size.height;
}



- (void)setBottom:(CGFloat)bottom {
    CGRect frame = self.frame;
    frame.origin.y = bottom - frame.size.height;
    self.frame = frame;
}



- (CGFloat)centerX {
    return self.center.x;
}



- (void)setCenterX:(CGFloat)centerX {
    self.center = CGPointMake(centerX, self.center.y);
}



- (CGFloat)centerY {
    return self.center.y;
}



- (void)setCenterY:(CGFloat)centerY {
    self.center = CGPointMake(self.center.x, centerY);
}



- (CGFloat)width {
    return self.frame.size.width;
}



- (void)setWidth:(CGFloat)width {
    CGRect frame = self.frame;
    frame.size.width = width;
    self.frame = frame;
}



- (CGFloat)height {
    return self.frame.size.height;
}



- (void)setHeight:(CGFloat)height {
    CGRect frame = self.frame;
    frame.size.height = height;
    self.frame = frame;
}



@end
